package com.edou.base.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {

	private static ObjectMapper mapper = null;

	static {
		mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
	}

	public static ObjectMapper getMapper() {
		return mapper;
	}

	// 将对象转换为JSON字符串
	public static String toJson(Object object) {
		ObjectMapper mapper = getMapper();
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 将JSON字符串转换为对象
	public static <T> T toObject(String json, Class<T> clazz) {
		ObjectMapper mapper = getMapper();
		try {
			return (T) mapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 将JSON字符串转换为对象
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T toObject(String json, TypeReference typeReference)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = getMapper();
		return (T) mapper.readValue(json, typeReference);
	}

	/**
	 * 将JSON字符串转换成集合
	 * @param in
	 * @param clsT
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static <T> List<T> getObjectsFromJson(String in, Class<T> clsT) throws IOException {
		ObjectMapper mapper = getMapper();
        JsonParser parser = mapper.getJsonFactory().createJsonParser(in);   
        JsonNode nodes = parser.readValueAsTree();
        List<T> list  = new ArrayList<T>(nodes.size());
        for(JsonNode node : nodes){
            list.add(mapper.readValue(node.toString(), clsT));
        }
        return list;
	}

}